#include <Arduino.h>
#include <Ticker.h>
#include "Button.h"
#include "Wifi_Ctrl.h"
#include "Menu_Ctrl.h"
#include "WatchDog.h"
#include "Aliyun.h"
#include "WS2812B.h"
#include "Led.h"
#include "Ze08Ch2o.h"
#include "Zph02.h"

/*静态全局变量*/

/*全局变量*/
extern uint8_t machine_rest_flag;
Ticker tickersecond;
volatile bool sec_flag = false;

/*局部函数*/
void Second_tick(void)
{
  sec_flag = true;
}

/*全局函数*/
void setup() 
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(10);

  //Serial.printf("main.cpp %d:ESP32 HEAP:%d\r\n",__LINE__,esp_get_free_heap_size());

  WiFi_Setup();

  //Serial.printf("\r\nmain.cpp %d:ESP32 HEAP:%d\r\n",__LINE__,esp_get_free_heap_size());

  Button_Init();

  //Serial.printf("\r\nmain.cpp %d:ESP32 HEAP:%d\r\n",__LINE__,esp_get_free_heap_size());

  WS2812B_Init();

  //Serial.printf("\r\nmain.cpp %d:ESP32 HEAP:%d\r\n",__LINE__,esp_get_free_heap_size());

  Led_Init();

  //Serial.printf("\r\nmain.cpp %d:ESP32 HEAP:%d\r\n",__LINE__,esp_get_free_heap_size());

  Ze08_Ch2o_Init();

  //Serial.printf("\r\nmain.cpp %d:ESP32 HEAP:%d\r\n",__LINE__,esp_get_free_heap_size());

  Zph02_Init();

  //Serial.printf("\r\nmain.cpp %d:ESP32 HEAP:%d\r\n",__LINE__,esp_get_free_heap_size());

  WatchDog_Init();

  //Serial.printf("main.cpp %d:ESP32 HEAP:%d\r\n",__LINE__,esp_get_free_heap_size());

  tickersecond.attach(1, Second_tick);

  delay(1000);


  Serial.println("loop start");

  //nightled_flag = true;
}

void loop() 
{
  // put your main code here, to run repeatedly:
  uint8_t menu_event = MENU_EVENT_NULL;

  Feed_Dog();

  if(sec_flag == true)
  {
    sec_flag = false;
    menu_event = MENU_EVENT_TICK;
  }

  uint8_t button_state = Get_Button_State();
  if(button_state != 0)
  {
    Serial.printf("\r\nmain.cpp %d:ESP32 HEAP1 %d\r\n",__LINE__, esp_get_free_heap_size());
    Serial.printf("button %d\r\n", button_state);
    menu_event = MENU_EVENT_BUTTON1 + button_state - 1;
    Serial.printf("menu_event:%d\r\n",menu_event);
  }

  menu_proc(menu_event);

  if(machine_rest_flag != MACHINE_CLOSE)
  {
    WiFi_Loop();

    Aliyun_Loop();

    Read_Ze08_Ch2o_Data();

    Read_ZPh02_Data();
  }

  Feed_Dog();
}